package com.lw.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

// 自定义数据源来获取数据
// 这里只要是存在一个自定义的 UserDetailsService ，那么security将会使用该实例进行配置
@Component
public class MyUserDetailsService implements UserDetailsService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 可以从任何地方获取数据
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查找用户信息
        logger.info("登录用户名:{}", username);
        String password = passwordEncoder.encode("123");
        logger.info("数据库密码{}", password);
        // 写死一个密码，赋予一个admin权限
        /**
         * isEnabled 账户是否启用
         * isAccountNonExpired 账户没有过期
         * isCredentialsNonExpired 身份认证是否是有效的
         * isAccountNonLocked 账户没有被锁定 （不开启，加密密码没法使用）
         */
        return new User(username, password,
                true, true, true, true,
                        AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}